import PubSub.*;

import org.omg.CORBA.*;
import org.omg.PortableServer.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;

public class BrokerImpl extends BrokerPOA {
	private ORB orb;
	private POA rootpoa;
	private NamingContextExt rootContext;
	private NamingContextExt topicContext;

	public BrokerImpl(ORB orb) {
		this.orb = orb;
		
		try {
			rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
			rootContext = NamingContextExtHelper.narrow(orb.resolve_initial_references("NameService"));
			topicContext = NamingContextExtHelper.narrow(rootContext.resolve(rootContext.to_name("Topic")));
		} catch(Exception e) {
			System.out.println("ERROR: "+e.getMessage());
		}
	}


	public void addTopic(String topicName) throws ExistentTopic {
		try {
			TopicImpl topicImpl = new TopicImpl(topicName, orb);
			org.omg.CORBA.Object topicRef = rootpoa.servant_to_reference(topicImpl);
			Topic topic = TopicHelper.narrow(topicRef);
			NameComponent[] topicPath = rootContext.to_name(topicName);
			topicContext.bind(topicPath, topic);
			System.out.println("Topic "+topicName+" bind successful");
		} catch(AlreadyBound e) {
			throw new ExistentTopic();
		} catch(Exception e) {
			e.printStackTrace();
		}

	}

	public void removeTopic(String topicName) throws NonExistentTopic {
		try {
			org.omg.CORBA.Object topicRef = topicContext.resolve_str(topicName);
			Topic topic = TopicHelper.narrow(topicRef);
			topic.eraseStatus();
			topicContext.unbind(rootContext.to_name(topicName));
			System.out.println("Topic "+topicName+" unbind successful");
		} catch(NotFound e) {
			throw new NonExistentTopic();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public String getHash(String text) {
		return Hash.getHashText(text);
	}

}